#include "Socket.hpp"
#include "Log.hpp"
#include <functional>
#include <sys/wait.h>
#include <unistd.h>
#include <iostream>
using namespace SocketModel;
using namespace LogModel;
using task = std::function<void(std::shared_ptr<Socket> &_sock, InetAddr &client)>;//接受信息和业务逻辑

class TcpServer
{
public:
    TcpServer(uint16_t port,task service):_port(port),_service(service),_isrunning(false),_ser_sock(std::make_unique<TcpSocket>()){
        _ser_sock->BuildTcpSocket(_port);
    }
    void Start(){
        _isrunning = true;
        while(_isrunning){
            InetAddr client;
            std::shared_ptr<Socket> peer = _ser_sock->AcceptOrDie(&client);
            if(peer == nullptr) {
                continue;
            }
            Log(LogLevel::DEBUG)<<"accept success";

            pid_t id = fork();
            if(id<0){
                Log(LogLevel::FATAL)<<"fork erro";
                exit(FORK_ERR);
            }
            if(id == 0){
                _ser_sock->Close();
                pid_t _id = fork();
                if(_id>0) exit(OK);
                //让子子进程执行需要的业务操作
                _service(peer,client);
            }else{
                peer->Close();
                pid_t rid = ::waitpid(id,nullptr,0);
                (void)rid;
            }

        }
        _isrunning = false;
    }
private:
    std::unique_ptr<Socket> _ser_sock;
    uint16_t _port;
    bool _isrunning;
    task _service;
};